package com.coastline.fruit.common.task;

import com.coastline.fruit.common.thread.TaskScheduledThread;
import org.springframework.scheduling.annotation.EnableScheduling;
import org.springframework.scheduling.annotation.SchedulingConfigurer;
import org.springframework.scheduling.config.ScheduledTaskRegistrar;
import org.springframework.scheduling.support.CronTrigger;

import java.util.TimeZone;

/**
 * 定时任务公共执行方法
 *
 * @author Coastline
 * @date 2025/1/10 22:07
 */
@EnableScheduling
public abstract class DynamicAbstractTask extends AbstractTask implements SchedulingConfigurer {

    /**
     * 设置定时任务动态执行时间
     *
     * @param taskRegistrar the registrar to be configured.
     */
    @Override
    public void configureTasks(ScheduledTaskRegistrar taskRegistrar) {
        taskRegistrar.setScheduler(TaskScheduledThread.getExecutorService());
        taskRegistrar.addTriggerTask(this::execute, triggerContext -> new CronTrigger(getCron(),
                TimeZone.getDefault().toZoneId()).nextExecutionTime(triggerContext));
    }

    /**
     * 定时任务执行时间
     *
     * @return cron 执行时间cron表达式
     */
    protected abstract String getCron();
}
